#include "head.h"
#include "queue.h"


int pipe_fd[2];

void func(int num){
    write(pipe_fd[1],"1",1);
    return;
}

int main(){

    pipe(pipe_fd);
    if(fork() != 0){
        signal(2,func);
        wait(NULL);

        close(pipe_fd[0]);
        close(pipe_fd[1]);
        exit(0);
    }

    printf("pid = %d\n",getpid());
    int ret = setpgid(0,0);
    ERROR_CHECK(ret,-1,"setpgid");
    close(pipe_fd[1]);

    status_t status;
    init_status(&status,4);

    init_thread_pool(&status);

    int socket_fd;
    char* port = "8080";
    char* ip = "192.168.131.128";
    init_tcp(&socket_fd,port,ip);

    int epoll_fd = epoll_create(1);

    add_to_epoll(epoll_fd,socket_fd);
    add_to_epoll(epoll_fd,pipe_fd[0]);


    while(1){

        struct epoll_event epoll_list[10];
        memset(epoll_list,0,sizeof(epoll_list));
        int epoll_num = epoll_wait(epoll_fd,epoll_list,10,-1);

        for(int i=0;i<epoll_num;i++){
            int fd = epoll_list[i].data.fd;
            if(fd == socket_fd){
                int net_fd = accept(socket_fd,NULL,NULL);
                
                pthread_mutex_lock(&status.lock);
                enQueue(&status.queue,net_fd);

                pthread_cond_signal(&status.cond);
                pthread_mutex_unlock(&status.lock);

            }else if(fd == pipe_fd[0]){
                printf("catch signal\n");
                char buf[20];
                read(pipe_fd[0],buf,sizeof(buf));

                pthread_mutex_lock(&status.lock);
                status.exit_flag = 1;
                pthread_cond_broadcast(&status.cond);
                pthread_mutex_unlock(&status.lock);

                for(int k=0;k<status.thread_num;k++){
                    pthread_join(status.thread_ids[k],NULL);
                }
                pthread_exit(NULL);
            }

        }

    }

    close(epoll_fd);
    close(socket_fd);
    return 0;

}










